package com.example.my_rabbitmq_high_demo.message;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 生产者
 * @Author: GaoJian
 * @Date: 2022/7/4 01:33
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1、创建连接工厂，设置属性
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");

        //2、创建连接
        Connection connection = factory.newConnection();

        //3、使用connection创建channel
        Channel channel = connection.createChannel();

        //4、通过channel发送消息
        String msg = "hello rabbitmq";
        AMQP.BasicProperties properties = new AMQP.BasicProperties();
        HashMap<String, Object> headers = new HashMap<>();
        headers.put("name", "裘千仞");
        properties = properties.builder()
                //设置编码为UTF8
                .contentEncoding("UTF-8")
                //设置自定义Header
                .headers(headers)
                //设置失效时间
                .expiration("5000").build();

        for (int i = 0; i < 5; i++) {
            //不指定exchange的情况下，使用默认的exchange，routingKey与队列名相等
            channel.basicPublish("", "test01", properties, msg.getBytes());
        }

        //5、关闭连接
        channel.close();
        connection.close();
    }
}
